<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Elasticsearch 自动补全演示</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }

        .header p {
            font-size: 1.2em;
            opacity: 0.9;
        }

        .content {
            padding: 40px;
        }

        .search-section {
            margin-bottom: 40px;
        }

        .search-section h2 {
            color: #333;
            margin-bottom: 20px;
            font-size: 1.8em;
        }

        .search-box {
            position: relative;
            margin-bottom: 20px;
        }

        .search-input {
            width: 100%;
            padding: 15px 20px;
            border: 2px solid #e1e5e9;
            border-radius: 10px;
            font-size: 16px;
            transition: all 0.3s ease;
        }

        .search-input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .suggestions {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: white;
            border: 1px solid #e1e5e9;
            border-top: none;
            border-radius: 0 0 10px 10px;
            max-height: 300px;
            overflow-y: auto;
            z-index: 1000;
            display: none;
        }

        .suggestion-item {
            padding: 12px 20px;
            cursor: pointer;
            border-bottom: 1px solid #f0f0f0;
            transition: background-color 0.2s ease;
        }

        .suggestion-item:hover {
            background-color: #f8f9fa;
        }

        .suggestion-item:last-child {
            border-bottom: none;
        }

        .suggestion-text {
            font-weight: 500;
            color: #333;
        }

        .suggestion-highlight {
            color: #667eea;
            font-weight: bold;
        }

        .suggestion-meta {
            font-size: 0.9em;
            color: #666;
            margin-top: 5px;
        }

        .controls {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }

        .control-group {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .control-group label {
            font-weight: 500;
            color: #555;
        }

        .control-group select,
        .control-group input {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
            text-align: center;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-secondary:hover {
            background: #5a6268;
        }

        .results {
            margin-top: 30px;
        }

        .result-item {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 15px;
            transition: all 0.3s ease;
        }

        .result-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .result-title {
            font-size: 1.2em;
            font-weight: 600;
            color: #333;
            margin-bottom: 10px;
        }

        .result-meta {
            display: flex;
            gap: 20px;
            font-size: 0.9em;
            color: #666;
        }

        .loading {
            text-align: center;
            padding: 20px;
            color: #666;
        }

        .error {
            background: #f8d7da;
            color: #721c24;
            padding: 15px;
            border-radius: 8px;
            margin-top: 20px;
        }

        .stats {
            background: #e3f2fd;
            padding: 20px;
            border-radius: 8px;
            margin-top: 20px;
        }

        .stats h3 {
            color: #1976d2;
            margin-bottom: 10px;
        }

        .stats p {
            color: #555;
            margin: 5px 0;
        }

        @media (max-width: 768px) {
            .container {
                margin: 10px;
                border-radius: 10px;
            }
            
            .content {
                padding: 20px;
            }
            
            .controls {
                flex-direction: column;
            }
            
            .header h1 {
                font-size: 2em;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🔍 Elasticsearch 自动补全演示</h1>
            <p>体验强大的搜索自动补全功能</p>
        </div>

        <div class="content">
            <div class="search-section">
                <h2>智能搜索</h2>
                
                <div class="controls">
                    <div class="control-group">
                        <label for="indexType">搜索类型</label>
                        <select id="indexType">
                            <option value="product">商品</option>
                            <option value="city">城市</option>
                            <option value="user">用户</option>
                        </select>
                    </div>
                    
                    <div class="control-group">
                        <label for="maxResults">最大结果数</label>
                        <input type="number" id="maxResults" value="10" min="1" max="50">
                    </div>
                    
                    <div class="control-group">
                        <label for="minLength">最小字符数</label>
                        <input type="number" id="minLength" value="2" min="1" max="10">
                    </div>
                </div>

                <div class="search-box">
                    <input type="text" id="searchInput" class="search-input" 
                           placeholder="输入关键词开始搜索..." autocomplete="off">
                    <div id="suggestions" class="suggestions"></div>
                </div>

                <div style="margin-top: 20px;">
                    <button class="btn btn-primary" onclick="initData()">初始化测试数据</button>
                    <button class="btn btn-secondary" onclick="clearResults()">清空结果</button>
                </div>
            </div>

            <div id="results" class="results"></div>
            <div id="stats" class="stats" style="display: none;"></div>
        </div>
    </div>

    <script>
        let searchTimeout;
        const API_BASE = '/api/autocomplete';

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            const searchInput = document.getElementById('searchInput');
            const suggestions = document.getElementById('suggestions');
            
            // 搜索输入事件
            searchInput.addEventListener('input', function() {
                const keyword = this.value.trim();
                
                if (keyword.length === 0) {
                    hideSuggestions();
                    return;
                }
                
                // 防抖处理
                clearTimeout(searchTimeout);
                searchTimeout = setTimeout(() => {
                    performSearch(keyword, true);
                }, 300);
            });

            // 点击外部隐藏建议
            document.addEventListener('click', function(e) {
                if (!searchInput.contains(e.target) && !suggestions.contains(e.target)) {
                    hideSuggestions();
                }
            });

            // 键盘事件
            searchInput.addEventListener('keydown', function(e) {
                if (e.key === 'Escape') {
                    hideSuggestions();
                }
            });
        });

        // 执行搜索
        async function performSearch(keyword, showSuggestions = false) {
            const indexType = document.getElementById('indexType').value;
            const maxResults = parseInt(document.getElementById('maxResults').value);
            const minLength = parseInt(document.getElementById('minLength').value);

            if (keyword.length < minLength) {
                if (showSuggestions) hideSuggestions();
                return;
            }

            try {
                const response = await fetch(`${API_BASE}/${indexType}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        keyword: keyword,
                        indexType: indexType,
                        size: maxResults,
                        minPrefixLength: minLength,
                        highlight: true
                    })
                });

                const result = await response.json();
                
                if (result.success) {
                    const data = result.data;
                    
                    if (showSuggestions) {
                        showSuggestionsList(data.suggestions);
                    } else {
                        showResults(data);
                    }
                } else {
                    showError(result.message || '搜索失败');
                }
            } catch (error) {
                console.error('搜索错误:', error);
                showError('网络错误，请检查连接');
            }
        }

        // 显示建议列表
        function showSuggestionsList(suggestions) {
            const suggestionsDiv = document.getElementById('suggestions');
            
            if (suggestions.length === 0) {
                hideSuggestions();
                return;
            }

            suggestionsDiv.innerHTML = suggestions.map(item => `
                <div class="suggestion-item" onclick="selectSuggestion('${item.text}')">
                    <div class="suggestion-text">${item.highlightedText || item.text}</div>
                    <div class="suggestion-meta">
                        评分: ${item.score?.toFixed(2) || 'N/A'} | 类型: ${item.type}
                    </div>
                </div>
            `).join('');

            suggestionsDiv.style.display = 'block';
        }

        // 选择建议
        function selectSuggestion(text) {
            document.getElementById('searchInput').value = text;
            hideSuggestions();
            performSearch(text, false);
        }

        // 隐藏建议
        function hideSuggestions() {
            document.getElementById('suggestions').style.display = 'none';
        }

        // 显示搜索结果
        function showResults(data) {
            const resultsDiv = document.getElementById('results');
            const statsDiv = document.getElementById('stats');
            
            if (data.suggestions.length === 0) {
                resultsDiv.innerHTML = '<div class="loading">没有找到相关结果</div>';
                statsDiv.style.display = 'none';
                return;
            }

            resultsDiv.innerHTML = data.suggestions.map(item => {
                const source = item.source;
                let metaInfo = '';
                
                if (source.category) {
                    metaInfo += `分类: ${source.category} | `;
                }
                if (source.brand) {
                    metaInfo += `品牌: ${source.brand} | `;
                }
                if (source.price) {
                    metaInfo += `价格: ¥${source.price} | `;
                }
                if (source.province) {
                    metaInfo += `省份: ${source.province} | `;
                }
                if (source.profession) {
                    metaInfo += `职业: ${source.profession} | `;
                }
                
                metaInfo += `评分: ${item.score?.toFixed(2) || 'N/A'}`;

                return `
                    <div class="result-item">
                        <div class="result-title">${item.highlightedText || item.text}</div>
                        <div class="result-meta">${metaInfo}</div>
                    </div>
                `;
            }).join('');

            // 显示统计信息
            statsDiv.innerHTML = `
                <h3>搜索统计</h3>
                <p>找到 ${data.total} 个结果</p>
                <p>搜索耗时: ${data.took} 毫秒</p>
                <p>搜索状态: ${data.success ? '成功' : '失败'}</p>
            `;
            statsDiv.style.display = 'block';
        }

        // 显示错误信息
        function showError(message) {
            const resultsDiv = document.getElementById('results');
            resultsDiv.innerHTML = `<div class="error">错误: ${message}</div>`;
            document.getElementById('stats').style.display = 'none';
        }

        // 初始化测试数据
        async function initData() {
            try {
                const response = await fetch(`${API_BASE}/init-data`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                });

                const result = await response.json();
                
                if (result.success) {
                    alert('测试数据初始化成功！');
                } else {
                    alert('初始化失败: ' + result.message);
                }
            } catch (error) {
                console.error('初始化错误:', error);
                alert('网络错误，请检查连接');
            }
        }

        // 清空结果
        function clearResults() {
            document.getElementById('results').innerHTML = '';
            document.getElementById('stats').style.display = 'none';
            document.getElementById('searchInput').value = '';
            hideSuggestions();
        }
    </script>
</body>
</html>
